package com.hmjk.health.card;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap.OnMapClickListener;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMarkerDragListener;
import com.baidu.mapapi.map.BaiduMapOptions;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.hmjk.health.HealthApp;
import com.hmjk.health.R;

public class MapFenceActivity extends Activity implements OnClickListener, OnMarkerClickListener, OnMarkerDragListener, OnMapClickListener{
	private final String TAG = MapFenceActivity.class.getSimpleName();
	
	private HealthApp mApp = null;
	private MapView mMapView = null;
	private BaiduMap mBaiduMap = null;
	private Marker mMarker = null;
	GeoCoder mSearch = null;
	InfoWindow iWindow = null;
	TextView addrView = null;
	LocationClient mLocClient = null;
	RelativeLayout relativeLayout = null;
	
	private int markerHight = 0;
	
	LatLng markerPoint = null;
	String markerAddr = "";
	
	private double centerLat = 0.0f, centerLng = 0.0f;

	public MapFenceActivity() {
		// TODO Auto-generated constructor stub
	}
	
	private void logd(String info){
		Log.d(TAG,info);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mApp = (HealthApp)getApplication();
        
        BaiduMapOptions mapOptions = new BaiduMapOptions();
        mMapView = new MapView(this, mapOptions);// 获取地图控件引用
        setContentView(mMapView);
        
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        View view = LayoutInflater.from(this).inflate(R.layout.map_fence,null);//自己的xml
        this.addContentView(view, params);
        
        ImageButton backBut = (ImageButton)findViewById(R.id.back);
		backBut.setOnClickListener(this);

		mSearch = GeoCoder.newInstance();
		OnGetGeoCoderResultListener listener = new OnGetGeoCoderResultListener() {

			@Override
			public void onGetGeoCodeResult(GeoCodeResult result) {
				// TODO Auto-generated method stub
				markerPoint = result.getLocation();
			}

			@Override
			public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
				// TODO Auto-generated method stub
				markerAddr = result.getAddress();
				isIWindowShow = showInfoWindow(true);
			}
			
		};
		mSearch.setOnGetGeoCodeResultListener(listener);
		
		// 开启定位图层
		mBaiduMap = mMapView.getMap();
		
		//地图定位
		mBaiduMap.setMyLocationEnabled(true);
		mLocClient = new LocationClient(this);
		mLocClient.registerLocationListener(new BDLocationListener() {
			
			@Override
			public void onReceiveLocation(BDLocation location) {
				// TODO Auto-generated method stub
				LatLng lc = new LatLng(location.getLatitude(), location.getLongitude());
				MapStatusUpdate status = MapStatusUpdateFactory.newLatLng(lc);
				mBaiduMap.animateMapStatus(status);
				//mMarker.setPosition(lc);
				mBaiduMap.setMyLocationEnabled(false);
				mLocClient.stop();
			}
		});
		LocationClientOption locoption = new LocationClientOption();
		locoption.setOpenGps(true);// 打开gps
		locoption.setCoorType("bd09ll"); // 设置坐标类型
		locoption.setScanSpan(5000);
		mLocClient.setLocOption(locoption);
		
		centerLat = this.getIntent().getExtras().getDouble("fencelat");
		centerLng = this.getIntent().getExtras().getDouble("fencelng");
		markerPoint = new LatLng(centerLat, centerLng);
		mBaiduMap.animateMapStatus(MapStatusUpdateFactory.zoomTo(17));
		if((centerLat == 0.0f) && (centerLng == 0.0f)){
			//centerLat = 31.17051;
			//centerLng = 121.445193;
			mLocClient.start();
			
		}else{
			MapStatusUpdate status = MapStatusUpdateFactory.newLatLng(new LatLng(centerLat, centerLng));
			mBaiduMap.animateMapStatus(status);
			mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(markerPoint));
		}
		//LatLng point = new LatLng(centerLat + 0.0060, centerLng + 0.0065);
		
		//getResources().getDrawable(R.drawable.marker).
		Bitmap bg = BitmapFactory.decodeResource(getResources(), R.drawable.marker);
		markerHight = bg.getHeight();
		bg.recycle();
		System.gc();
		//float f = getResources().getDisplayMetrics().density;
		//markerHight = (int)(f*60);
		//构建Marker图标
		BitmapDescriptor centerTip = BitmapDescriptorFactory.fromResource(R.drawable.marker);
		
		//构建MarkerOption，用于在地图上添加Marker
		OverlayOptions option = new MarkerOptions().position(markerPoint)
				.icon(centerTip)
				.draggable(true);
		mMarker = (Marker)mBaiduMap.addOverlay(option);
		mMarker.setDraggable(true);
		mBaiduMap.setOnMarkerDragListener(this);
		mBaiduMap.setOnMarkerClickListener(this);
		mBaiduMap.setOnMapClickListener(this);

		addrView = new TextView(this);
		relativeLayout = new RelativeLayout(this);
		relativeLayout.setBackgroundResource(R.drawable.map_tips_white_bg);
		RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(Dp2Px(150f), Dp2Px(60f));
		layoutParams.leftMargin = 30;
		layoutParams.rightMargin = 30;
		layoutParams.topMargin = 15;
		layoutParams.bottomMargin = 15;
		layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
		addrView.setLayoutParams(layoutParams);
		relativeLayout.addView(addrView);
		relativeLayout.setClickable(true);
		relativeLayout.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				showInfoWindow(false);
			}
		});
		
		addrView.setSingleLine(false);
		addrView.setMaxLines(2);
		addrView.setGravity(Gravity.CENTER);
		addrView.setText(R.string.analyzing);
		addrView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
		addrView.setTextColor(0xFF444444);
		//Drawable drawable = getResources().getDrawable(R.drawable.marker);
		//drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
		//addrView.setCompoundDrawables(drawable, null, null, null);

		//iWindow = new InfoWindow(addrView, markerPoint, 40);
		//mBaiduMap.showInfoWindow(iWindow);
		/*
		iWindow = new InfoWindow(centerTip, markerPoint, 0, 
				new InfoWindow.OnInfoWindowClickListener() {
					
					@Override
					public void onInfoWindowClick() {
						// TODO Auto-generated method stub
						mBaiduMap.hideInfoWindow();
					}
				});
		*/
		
	}
	
	@Override
	protected void onDestroy() {
		mLocClient.stop();
		mBaiduMap.setMyLocationEnabled(false);		
		mMapView.onDestroy();
		mMapView = null;
		super.onDestroy();
	}
	
	private int Dp2Px(float dp) { 
	    final float scale = getResources().getDisplayMetrics().density; 
	    return (int) (dp * scale + 0.5f); 
	}

	private boolean isIWindowShow = false;
	@Override
	public boolean onMarkerClick(Marker m) {
		// TODO Auto-generated method stub
		logd("onMarkerClick");
		/*
		if(isIWindowShow){
			mBaiduMap.hideInfoWindow();
			isIWindowShow = false;
		}else {
			
			if(markerAddr.trim().isEmpty() == false){
				addrView.setText(markerAddr);
				mBaiduMap.showInfoWindow(iWindow);
				isIWindowShow = true;
			}
		}*/
		isIWindowShow = showInfoWindow(!isIWindowShow);
		
		return false;
	}
	
	private boolean showInfoWindow(boolean show){
		if(show){
			if(markerAddr.trim().isEmpty()){
				markerAddr = getResources().getString(R.string.analyzing);
			}
			addrView.setText(markerAddr);
			int offset = - markerHight;
			InfoWindow mInfoWindow = new InfoWindow(relativeLayout, markerPoint, offset);
			mBaiduMap.showInfoWindow(mInfoWindow);
			return true;
		}else {
			mBaiduMap.hideInfoWindow();
			return false;
		}
	}

	private void cancelAndCommit(){
		if((centerLat == markerPoint.latitude) && (centerLng == markerPoint.longitude)){
			finish();
		}else {
			String msg = markerAddr;
			if(msg.isEmpty() || msg.equals(getResources().getString(R.string.analyzing))){
				msg = getResources().getString(R.string.longitude, "" + markerPoint.longitude) + "\n" 
						+ getResources().getString(R.string.latitude, "" + markerPoint.latitude);
			}
			mApp.showCustomizedDialog(this, getResources().getString(R.string.fence_confirm_title), msg, 
					getResources().getString(R.string.save_and_exit), getResources().getString(R.string.exit), 
					new OnClickListener() {
						
						@Override
						public void onClick(View view) {
							// TODO Auto-generated method stub
							if(view.getId() == R.id.alert_but1){
								String addr = markerAddr;
								if(addr.isEmpty() || addr.equals(getResources().getString(R.string.analyzing))){
									addr = "" + markerPoint.longitude + markerPoint.latitude;
								}
								Intent intent = new Intent();
								intent.putExtra("lat", markerPoint.latitude);
								intent.putExtra("lng", markerPoint.longitude);
								intent.putExtra("address", addr);
								setResult(RESULT_OK, intent);
								finish();
							}else if(view.getId() == R.id.alert_but2){
								finish();
							}
						}
					});
		}
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		logd("onClick");
		switch(v.getId()){
		case R.id.back:{
			cancelAndCommit();
			
		}break;
		
		}
	}

	@Override
	public void onMarkerDrag(Marker m) {
		// TODO Auto-generated method stub
		//logd("onMarkerDrag");
	}

	@Override
	public void onMarkerDragEnd(Marker m) {
		// TODO Auto-generated method stub
		logd("onMarkerDragEnd");
		markerPoint = m.getPosition();
		mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(markerPoint));
	}

	@Override
	public void onMarkerDragStart(Marker arg0) {
		// TODO Auto-generated method stub
		logd("onMarkerDragStart");
		isIWindowShow = showInfoWindow(false);
	}

	@Override
	public void onMapClick(LatLng point) {
		// TODO Auto-generated method stub
		logd("onMapClick");
		final LatLng tmpLng = point;
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.fence_center_confirm);
		builder.setIcon(R.drawable.marker);
		builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener(){

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				mMarker.setPosition(tmpLng);
				markerPoint = tmpLng;
				markerAddr = "";
				isIWindowShow = showInfoWindow(true);
				mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(markerPoint));
			}
			
		});
		builder.setNegativeButton(R.string.back, new DialogInterface.OnClickListener(){

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				
			}
			
		});
		builder.create().show();
	}

	@Override
	public boolean onMapPoiClick(MapPoi poi) {
		// TODO Auto-generated method stub
		logd("onMapPoiClick");
		final LatLng tmpLng = poi.getPosition();
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.fence_center_confirm);
		builder.setIcon(R.drawable.marker);
		builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener(){

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				mMarker.setPosition(tmpLng);
				markerPoint = tmpLng;
				markerAddr = "";
				isIWindowShow = showInfoWindow(true);
				mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(markerPoint));
			}
			
		});
		builder.setNegativeButton(R.string.back, new DialogInterface.OnClickListener(){

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				
			}
			
		});
		builder.create().show();
		return false;
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event){
		if(keyCode == KeyEvent.KEYCODE_BACK){
			cancelAndCommit();
			return true;
		}
		return false;
	}


}
